package com.xf.auth.service.impl;

import com.xf.common.core.domain.Constants;
import com.xf.common.core.enums.UserCacheKeyEnum;
import com.xf.common.redis.cache.DmpRedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.time.Duration;

/**
 * @author Yuuki
 */
@Slf4j
@Service
public class RedisClientDetailsService extends JdbcClientDetailsService {
    /**
     * 缓存 client的 redis key，这里是 hash结构存储
     */


    private final DmpRedisCache redisCache;

    public RedisClientDetailsService(DataSource dataSource, DmpRedisCache redisCache) {
        super(dataSource);
        this.redisCache = redisCache;
    }

    /**
     * 查询缓存客户端
     *
     * @param clientId
     * @return
     * @throws InvalidClientException
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
        return redisCache.getEx(UserCacheKeyEnum.CLIENTDETAILS.getKey(clientId),
                Duration.ofSeconds(Constants.CLIENT_DETAILS), () -> super.loadClientByClientId(clientId));
    }
}
